from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from core.exceptions import CustomException, validation_exception_handler
from core.middleware import exception_handler
from schemas.response import ResponseModel
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from routers import websocket, user, message
from core.socket_manager import AsyncSocketManager
import asyncio
from contextlib import asynccontextmanager

# 由于fastapi的文件是提供的CDN为国外的网址，偶尔可能存在网络延迟，导致docs为空白
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)

# 创建Socket服务器实例
socket_server = AsyncSocketManager(host='0.0.0.0', port=9999)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    处理应用的生命周期事件
    """
    # 启动时执行
    print("正在启动应用...")
    # 在后台任务中启动Socket服务器
    asyncio.create_task(socket_server.start())
    
    yield  # FastAPI 运行中
    
    # 关闭时执行
    print("正在关闭应用...")
    await socket_server.stop()

# 使用 lifespan 替代 on_event
# app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None)
app = FastAPI()

# 注册验证错误处理器
app.add_exception_handler(RequestValidationError, validation_exception_handler)

# 注册全局异常处理器
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    return await exception_handler(request, exc)

import os
from fastapi.staticfiles import StaticFiles
# 注册静态文件目录，在main.py同级目录下创建static文件夹
static_dir = os.path.dirname(os.path.abspath(__file__))
app.mount("/static",StaticFiles(directory=f"{static_dir}/static"), name="static")

# 加入路由/docs
@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        # openapi_url="/static/openapi.json",
        title=app.title + " - Swagger UI",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css",
    )

# 注册WebSocket路由
app.include_router(websocket.router)
app.include_router(user.user_app)
app.include_router(message.router)
from routers.securet_test import secure_router
app.include_router(secure_router,tags=["securet_test"])

# @app.get("/health", response_model=ResponseModel)
# async def health_check():
#     """健康检查接口，用于性能测试"""
#     return ResponseModel(
#         code=200,
#         msg="服务正常运行中"
#     )

if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app", host='0.0.0.0', port=8000, reload=True)